package org.finesys.ai.controller.chat;

import java.util.List;

import org.finesys.ai.core.chat.ChatCompletionResponse;
import org.finesys.ai.core.image.GenerateImagesResponse;
import org.finesys.ai.dto.ChatImageReq;
import org.finesys.ai.dto.ChatReq;
import org.finesys.ai.entity.AigcMessages;
import org.finesys.ai.service.AigcChatService;
import org.finesys.ai.service.AigcMessagesService;
import org.finesys.common.core.module.R;
import org.finesys.common.security.core.util.SecurityUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import lombok.RequiredArgsConstructor;
import reactor.core.publisher.Flux;

@RestController
@RequestMapping
@RequiredArgsConstructor
@SecurityRequirement(name = HttpHeaders.AUTHORIZATION)
public class AigcChatController {
    private final AigcChatService aigcChatService;
    private final AigcMessagesService aigcMessagesService;

    /**
     * 聊天完成接口
     * 该接口用于处理聊天请求，并返回聊天完成的响应结果
     *
     * @param chatReq 聊天请求对象，包含聊天相关的输入信息
     * @return 返回Flux类型的ChatCompletionResponse对象，表示聊天完成的响应流
     */
    @PostMapping(value = "/chat/completions", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<ChatCompletionResponse> chatCompletion(@RequestBody ChatReq chatReq) {
        return aigcChatService.chatFluxCompletion(chatReq);
    }

    @PostMapping(value = "/chat/image", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<GenerateImagesResponse> chatImage(@RequestBody ChatImageReq chatImageReq) {
        return aigcChatService.chatImage(chatImageReq);
    }

    @GetMapping("/chat/messages/{conversationId}")
    public R<?> getMessages(@PathVariable String conversationId) {
        String userId = SecurityUtils.getUserId();
        List<AigcMessages> messages = aigcMessagesService.getMessages(conversationId, userId);
        return R.success(messages);
    }

}
